package com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.risking

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.Typeface
import android.os.Bundle
import android.text.Spannable
import android.text.SpannableString
import android.text.Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
import android.text.style.ForegroundColorSpan
import android.text.style.RelativeSizeSpan
import android.text.style.StyleSpan
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.helasasa.maxfunds.lineofcredit.cashloan.databinding.ActivityGhanaRiskingBinding
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.http.hitPoint
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.risking.subview.IRiskingGhanaProcessBarListener
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.subview.HotlineGhanaDialog
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.tabhome.TabHomeGhanaActivity


class RiskingGhanaActivity : AppCompatActivity() {

    private lateinit var riskingViewModel: RiskingGhanaViewModel
    private lateinit var binding: ActivityGhanaRiskingBinding

    @SuppressLint("NotifyDataSetChanged")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // 数据模型
        riskingViewModel = ViewModelProvider(this)[RiskingGhanaViewModel::class.java]

        // 关联布局
        binding = ActivityGhanaRiskingBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // 用到的控件
        val back = binding.navbarLeft
        val hotline = binding.navbarRight
        val loading = binding.loading
        val remindProcess = binding.remindProcess
        val cutdown = binding.cutdown

        // 动画间隔回调
        val tickListener = object : IRiskingGhanaProcessBarListener {
            @SuppressLint("SetTextI18n")
            override fun onTick(tick: Int) {
                runOnUiThread {
                    println("=====tick:$tick")
                    val curText = 15 - tick
                    cutdown.text = "${curText}s"

                    if (tick % 12 == 0) {
                        println("==12秒查询状态")
                        riskingViewModel.mainProcess()
                    }
                }
            }

            override fun onCompleted() {
                riskingViewModel.mainProcess()
            }
        }
        remindProcess.addListener(tickListener)

        // 页面loading状态接口监听
        riskingViewModel.loadingResult.observe(this@RiskingGhanaActivity, Observer {
            val loadingResult = it ?: return@Observer

            if (loadingResult) {
                loading.visibility = View.VISIBLE
            } else {
                loading.visibility = View.GONE
            }
        })

        // 页面详情接口监听
        riskingViewModel.pageDetailResult.observe(this@RiskingGhanaActivity, Observer {
            val pageDetailResult = it ?: return@Observer

            loading.visibility = View.GONE
            if (pageDetailResult.error != null) {
                // TODO: 失败
                showMessage(pageDetailResult.error)
            }
            if (pageDetailResult.start != null) {
                // TODO: 开始动画
                remindProcess.start()
            }
            if (pageDetailResult.end != null) {
                // TODO: 成功
            }
        })

        // 流程接口监听
        riskingViewModel.mainProcessResult.observe(this@RiskingGhanaActivity, Observer {
            val mainProcessResult = it ?: return@Observer

            loading.visibility = View.GONE
            if (mainProcessResult.error != null) {
                showMessage(mainProcessResult.error)
            }

            if (mainProcessResult.success != null) {
                riskingViewModel.nextRouter(mainProcessResult.success)
            }
        })

        // 页面需要跳转监听
        riskingViewModel.nextRouterResult.observe(this@RiskingGhanaActivity, Observer {
            val nextRouterResult = it ?: return@Observer

            loading.visibility = View.GONE
            startNextActivity(nextRouterResult.nextPage)
        })

        // 点击返回
        back.setOnClickListener {
            startNextActivity(TabHomeGhanaActivity::class.java)
        }

        // 点击客服
        hotline.setOnClickListener {
            // 客服弹框
            HotlineGhanaDialog().showNow(supportFragmentManager, "hotline")
            hitPoint("SHOW_HOTLINE")
        }

        // 更新页面UI
        updateSpanText()

        // 查询页面详情
        riskingViewModel.pageDetail()
    }

    override fun onDestroy() {
        binding.remindProcess.stop()
        super.onDestroy()
    }

    private fun updateSpanText() {
        val text = binding.tips.text.toString()
        val words = "15 seconds"
        val gStart = text.indexOf(words)
        if (gStart >= 0) {
            val gEnd = gStart + words.length
            val spanString = SpannableString(text)
            spanString.setSpan(
                RelativeSizeSpan(1.2F),
                gStart,
                gEnd,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
            )
            spanString.setSpan(
                ForegroundColorSpan(Color.parseColor("#5277D6")),
                gStart,
                gEnd,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
            )
            spanString.setSpan(StyleSpan(Typeface.BOLD), gStart, gEnd, SPAN_EXCLUSIVE_EXCLUSIVE)

            binding.tips.text = spanString
        }
    }

    override fun onResume() {
        super.onResume()
        hitPoint(type = this::class.java.simpleName, isPageStart = true)
    }

    override fun onPause() {
        super.onPause()
        hitPoint(type = this::class.java.simpleName, isPageEnd = true)
    }
}

fun Context.showMessage(message: String) {
    Toast.makeText(applicationContext, message, Toast.LENGTH_SHORT).show()
}

fun Context.startNextActivity(
    activity: Class<out AppCompatActivity>? = null,
    params: HashMap<String, String> = HashMap()
) {
    val nextActivity = activity ?: return
    try {
        val intent = Intent(this, nextActivity)
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_NEW_TASK)
        params.keys.forEach { gKey ->
            intent.putExtra(gKey, params[gKey])
        }
        startActivity(intent)
    } catch (e: Exception) {
        e.printStackTrace()
    }
}
